package com.suian.spring.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class JdkAopProxy implements InvocationHandler {
    private final Object target;
    private final List<MethodInterceptor> interceptors;//拦截器链

    public JdkAopProxy(Object target, List<MethodInterceptor> interceptors) {
        this.target = target;
        this.interceptors = interceptors;
    }

    //创建代理对象
    public static Object createProxy(Object target, List<MethodInterceptor> interceptors) {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new JdkAopProxy(target, interceptors)
        );
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //构建方法调用链子
        MethodInvocation invocation = new ReflectiveMethodInvocation(target, method, args, interceptors);
        return invocation.proceed();
    }
}
